package com.hornsun.repository;

import com.google.common.base.Preconditions;
import com.hornsun.util.StrUtil;
import com.hornsun.domain.constant.types.HealthBeansSource;
import com.hornsun.domain.dbo.HealthBeansRecord;
import com.hornsun.domain.dbo.HealthBeansRecordExample;
import com.hornsun.repository.mapper.HealthBeansRecordMapper;
import com.hornsun.repository.mapper.MemberWechatMapper;
import com.hornsun.util.LittleUtil;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
 * Created by 编译中... on 2018/3/26.
 */
@Repository
public class HealthBeansReposiory {

    @Resource
    private HealthBeansRecordMapper healthBeansRecordMapper;

    @Resource
    private MemberWechatMapper memberWechatMapper;

    @Resource
    private LittleUtil littleUtil;

    /**
     * 增加健康豆
     * @param count
     */
    public void addHealthBeans(String openid,int count){
        Preconditions.checkNotNull(openid);
        Preconditions.checkNotNull(count);
        memberWechatMapper.addHealthBeans(openid,count);
    }

    // 获取健康豆记录
    public List<HealthBeansRecord> getHealthBeansRecord(String openid,int page){
        HealthBeansRecordExample healthBeansRecordExample = new HealthBeansRecordExample();
        healthBeansRecordExample.setOrderByClause(StrUtil.toDesc("record_time"));
        HealthBeansRecordExample.Criteria criteria = healthBeansRecordExample.createCriteria();
        criteria.andOpenidEqualTo(openid);
        return healthBeansRecordMapper.selectByExampleWithRowbounds(healthBeansRecordExample, littleUtil.littleRowBounds(page));
    }

    //添加用户健康豆收支记录
    public void insertHealthBeansRecord(HealthBeansRecord healthBeansRecord){
            int count = healthBeansRecordMapper.insertSelective(healthBeansRecord);
            if (count!=1){
                throw new IllegalArgumentException("insert healthBeans failed by healthBeansRecord:"+healthBeansRecord);
            }
    }


    public boolean whetherSignIn(String openid){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();
        HealthBeansRecordExample healthBeansRecordExample = new HealthBeansRecordExample();
        HealthBeansRecordExample.Criteria criteria = healthBeansRecordExample.createCriteria();
        criteria.andOpenidEqualTo(openid).andSourceEqualTo(HealthBeansSource.SIGNIN.getName()).andRecordTimeGreaterThanOrEqualTo(zero);
        return healthBeansRecordMapper.countByExample(healthBeansRecordExample)==0;

    }





}
